package com.wsz.educenter.controller;

import com.google.gson.Gson;
import com.wsz.commonutils.JwtUtils;
import com.wsz.educenter.pojo.Member;
import com.wsz.educenter.service.MemberService;
import com.wsz.educenter.utils.ConstantWxUtils;
import com.wsz.educenter.utils.HttpClientUtils;
import com.wsz.servicebase.exceptionhandler.MyTestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private MemberService memberService;

    @GetMapping("/callback")
    public String callback(String code,String state){
        try {
            //向认证服务器发送请求换取access_token
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            String accessToken = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );

            String accessTokenInfo = HttpClientUtils.get(accessToken);

            Gson gson = new Gson();
            HashMap hashMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String)hashMap.get("access_token");
            String openid = (String) hashMap.get("openid");

            Member member = memberService.getOpenIdMember(openid);

            if(member == null){

                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";

                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );

                String userInfo = HttpClientUtils.get(userInfoUrl);
                HashMap hashMap1 = gson.fromJson(userInfo, HashMap.class);

                String nickname = (String) hashMap1.get("nickname");
                String headimgurl= (String) hashMap1.get("headimgurl");

                member = new Member();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);

                memberService.save(member);
            }
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyTestException(20001,"登陆失败");
        }
    }

    @GetMapping("/login")
    public String getWxCode(){
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "wsz"
        );
        return "redirect:" + url;
    }
}
